package cn.edu.imut.service;

import cn.edu.imut.bean.CategoryBean;
import cn.edu.imut.bean.ProductBean;
import cn.edu.imut.dao.ProductDao;

import java.util.List;
import java.util.Scanner;

public class ProductService {
    private final ProductDao productDao = new ProductDao();
    private final Scanner sc = new Scanner(System.in);


    /**
     * 按排序方式浏览商品（支持分页）
     */
    public void filterAndSortProducts() {
        try {
            System.out.println("请选择排序方式（销量、价格）：");
            String sortBy = sc.next();
            System.out.println("请输入分页起始位置（从0开始）：");
            int offset = getValidIntInput();
            System.out.println("请输入分页大小：");
            int limit = getValidIntInput();

            List<ProductBean> products = productDao.getSortedProducts(sortBy, offset, limit);

            if (products.isEmpty()) {
                System.out.println("没有符合条件的商品！");
            } else {
                System.out.println("以下是按照 " + sortBy + " 排序的商品列表：");
                products.forEach(System.out::println);
            }
        } catch (Exception e) {
            System.err.println("按排序方式浏览商品时发生错误：" + e.getMessage());
        }
    }

    /**
     * 搜索商品
     */
    public void searchProducts() {
        try {
            System.out.println("请输入商品关键词：");
            String keyword = sc.next();
            List<ProductBean> products = productDao.searchProducts(keyword);

            if (products.isEmpty()) {
                System.out.println("未找到与关键词 \"" + keyword + "\" 匹配的商品！");
            } else {
                System.out.println("以下是包含关键词 \"" + keyword + "\" 的商品列表：");
                products.forEach(System.out::println);
            }
        } catch (Exception e) {
            System.err.println("搜索商品时发生错误：" + e.getMessage());
        }
    }

    public void viewFavoriteProducts(String username) {
        try {
            System.out.println("正在获取用户名为 " + username + " 的收藏商品...");
            List<ProductBean> favoriteProducts = productDao.getFavoriteProductsByUsername(username);

            if (favoriteProducts.isEmpty()) {
                System.out.println("用户名为 " + username + " 的用户尚未收藏任何商品！");
            } else {
                System.out.println("用户名为 " + username + " 收藏的商品如下：");
                for (ProductBean product : favoriteProducts) {
                    System.out.println("商品ID：" + product.getProductId());
                    System.out.println("商品名称：" + product.getProductName());
                    System.out.println("分类ID：" + product.getCategoryId());
                    System.out.println("销量：" + product.getSalesVolume());
                    System.out.println("价格：" + product.getPrice());
                    System.out.println("库存：" + product.getStock());
                    System.out.println("分类名称：" + product.getCategoryName());
                    System.out.println("--------------------------------------");
                }
            }
        } catch (Exception e) {
            System.err.println("查看收藏商品时发生错误：" + e.getMessage());
        }
    }


    /**
     * 收藏商品
     */
    public void favoriteProduct(int userId) {
        try {
            System.out.println("请输入要收藏的商品ID：");
            int productId = sc.nextInt();

            // 检查是否已收藏
            if (productDao.isProductFavorited(userId, productId)) {
                System.out.println("您已收藏该商品！");
                return;
            }

            // 添加收藏
            if (productDao.addFavorite(userId, productId)) {
                System.out.println("商品收藏成功！");
            } else {
                System.out.println("商品收藏失败！");
            }
        } catch (Exception e) {
            System.err.println("收藏商品时发生错误：" + e.getMessage());
        }
    }
    public void favoriteProduct(int userId, int productId) {
        try {
            // 检查是否已收藏
            if (productDao.isProductFavorited(userId, productId)) {
                System.out.println("您已收藏该商品！");
                return;
            }

            // 添加收藏
            if (productDao.addFavorite(userId, productId)) {
                System.out.println("商品收藏成功！");
            } else {
                System.out.println("商品收藏失败！");
            }
        } catch (Exception e) {
            System.err.println("收藏商品时发生错误：" + e.getMessage());
        }
    }

    /**
     * 获取有效的整数输入
     */
    private int getValidIntInput() {
        while (true) {
            try {
                System.out.print("请输入：");
                return sc.nextInt();
            } catch (Exception e) {
                System.out.println("输入无效，请输入一个整数！");
                sc.nextLine(); // 清除缓冲区
            }
        }
    }

    public void viewProductDetails() {
        try {
            System.out.println("请输入商品ID：");
            int productId = getValidIntInput();
            ProductBean product = productDao.getProductDetails(productId);

            if (product != null) {
                System.out.println("商品详情如下：");
                System.out.println("商品ID：" + product.getProductId());
                System.out.println("商品名称：" + product.getProductName());
                System.out.println("分类ID：" + product.getCategoryId());
                System.out.println("销量：" + product.getSalesVolume());
                System.out.println("价格：" + product.getPrice());
                System.out.println("库存：" + product.getStock());
                System.out.println("描述：" + product.getCategoryName());
            } else {
                System.out.println("未找到该商品！");
            }
        } catch (Exception e) {
            System.err.println("查看商品详情时发生错误：" + e.getMessage());
        }
    }
    public void viewAllCategories() {
        List<CategoryBean> categories = productDao.getAllCategories();

        if (categories.isEmpty()) {
            System.out.println("当前没有商品分类！");
        } else {
            System.out.println("以下是所有商品分类：");
            categories.forEach(category -> {
                System.out.println("分类ID：" + category.getCategoryId());
                System.out.println("分类名称：" + category.getCategoryName());
                System.out.println("分类描述：" + category.getCategoryDescription());
                System.out.println("--------------------------------------");
            });
        }
    }
    // 显示所有分类信息
    public void displayAllCategories() {
        List<CategoryBean> categories = productDao.getAllCategories();

        if (categories.isEmpty()) {
            System.out.println("当前没有分类！");
        } else {
            System.out.println("以下是所有商品分类：");
            categories.forEach(category -> {
                System.out.println("分类ID：" + category.getCategoryId());
                System.out.println("分类名称：" + category.getCategoryName());
                System.out.println("分类描述：" + category.getCategoryDescription());
                System.out.println("----------------------------------");
            });
        }
    }

    // 按分类浏览商品
    public void browseByCategory() {
        try {
            // 显示所有分类信息
            displayAllCategories();

            System.out.println("请输入分类ID以查看该分类下的商品：");
            int categoryId = sc.nextInt();
            List<ProductBean> products = productDao.getProductsByCategory(categoryId);

            if (products.isEmpty()) {
                System.out.println("该分类下没有商品！");
            } else {
                System.out.println("以下是分类ID为 " + categoryId + " 的商品列表：");
                products.forEach(product -> {
                    System.out.println("商品ID：" + product.getProductId());
                    System.out.println("商品名称：" + product.getProductName());
                    System.out.println("分类名称：" + product.getCategoryName());
                    System.out.println("销量：" + product.getSalesVolume());
                    System.out.println("价格：" + product.getPrice());
                    System.out.println("库存：" + product.getStock());
                    System.out.println("----------------------------------");
                });
            }
        } catch (Exception e) {
            System.err.println("按分类浏览商品时发生错误：" + e.getMessage());
        }
    }


    public void displayAllProducts() {
        List<ProductBean> products = productDao.getAllProducts();
        if (products.isEmpty()) {
            System.out.println("当前没有商品！");
        } else {
            System.out.println("以下是所有商品信息：");
            products.forEach(product -> {
                System.out.println("商品详情如下：");
                System.out.println("商品名称：" + product.getProductName());
                System.out.println("分类名称：" + product.getCategoryName());  // 显示分类名称
                System.out.println("销量：" + product.getSalesVolume());
                System.out.println("价格：" + product.getPrice());
                System.out.println("库存：" + product.getStock());

            });
        }
    }

}
